package dao;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class BaseDao {
    private static String driver=null;
    private static String username=null;
    private static  String url=null;
    private static String password=null;

    protected Connection conn=null;
    protected PreparedStatement pstmt=null;
    protected ResultSet rs=null;

    //静态代码块
    static {
        into();
    }

    //读取配置文件
    public static void into(){
        try {
            //创建一个properties
            Properties properties=new Properties();
            String configFile="database.properties";
            InputStream is = dao.BaseDao.class.getClassLoader().getResourceAsStream(configFile);
            properties.load(is);


            driver=properties.getProperty("driver");
            url=properties.getProperty("url");
            username=properties.getProperty("username");
            password=properties.getProperty("password");

            // 加载jdbc驱动，要指定jdbc的驱动类 com.mysql.cj.jdbc.Driver
            Class.forName(driver);
        }catch(ClassNotFoundException e){
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }
    }

    /**
     * 链接数据库
     *
     * @return
     */
    public Connection getConnection() {
        try {
            conn= DriverManager.getConnection(url,username,password);
        }catch(SQLException e){
            e.printStackTrace();
        }
        return conn;
    }
    /**
     * 关闭连接
     * @param conn 数据库连接
     * @param pstmt SQL语句
     * @param rs 执行SQL语句
     */
    public void closeAll(Connection conn,PreparedStatement pstmt,ResultSet rs){
        try {
            if (rs != null){
                rs.close();
            }
            if (pstmt != null){
                pstmt.close();
            }
            if (conn != null){
                conn.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

}
